<!DOCTYPE html>
<html>
<head>
    <title>毕工的浇花系统</title>
    <style>
        .rectangle {
            width: 90%;
            height: 80px;
            border: 1px solid;
            background-color: #38f87e;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .text {
            font-size: 24px;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 90%;
            margin: 0 auto;
            border: 1px solid;
            background-color: #a8f5c4;
            margin-top: 10px;
            align-self: flex-start;
        }
        .settinglabel {
            margin-top: 10px;
            width: 70%;
            text-align: right;
        }
        #chart {
            width: 100%; /* 设置宽度为70% */
            height: 150px;
            margin: 0 auto; /* 水平居中对齐 */
        }
    </style>
    <script>
        // 保存数据到缓存
        function saveData() {
            var input = document.getElementById("textInput_ip");
            var text = input.value;
            localStorage.setItem("savedText", text); // 将文本保存到localStorage的"savedText"键中
            // input.value = ""; // 清空文本框内容
        }

        // 从缓存中读取数据
        function loadData() {
            var savedText = localStorage.getItem("savedText"); // 从localStorage中根据键"savedText"读取数据
            if (savedText) {
                var input = document.getElementById("textInput_ip");
                input.value = savedText; // 将读取的缓存内容显示在文本框中
            } else {
                alert("缓存为空");
            }
        }
        // 在页面加载完成时执行读取缓存的动作
        window.onload = function() {
            loadData();
        }

        function get_plant_settings() {
            document.getElementById('input_set').value = 0;
            document.getElementById('input_push_ip').value = 0;
            document.getElementById('input_push_period').value= 0;
            var xhr = new XMLHttpRequest();
            
            var input = document.getElementById("textInput_ip");
            var ip_str = input.value;
            var get_url = "get_plant.php/get?settings=1&&ip="+ip_str
            console.log("get_url=", get_url)
            // xhr.open("GET", "http://192.168.2.185/get?humidity=0", true);
            xhr.open("GET", get_url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var responseText = xhr.responseText;
                    var jsonObject = JSON.parse(responseText); // 解析 JSON 字符串为 JavaScript 对象
                    // var sssValue = jsonObject.设置; // 获取 "sss" 值
                    console.log("recv=",jsonObject.push_ip);
                    console.log("recv=",jsonObject.set_hmdt);
                    console.log("recv=",jsonObject.push_period);
                    document.getElementById('input_set').value = jsonObject.set_hmdt;
                    document.getElementById('input_push_ip').value = jsonObject.push_ip;
                    document.getElementById('input_push_period').value= jsonObject.push_period;
                   
                }
            };

            xhr.send();
        }
        function get_plant_status() {
            var xhr = new XMLHttpRequest();
            
            var input = document.getElementById("textInput_ip");
            var ip_str = input.value;
            var get_url = "get_plant.php/get?get=1&&ip="+ip_str
            console.log("get_url=", get_url)
            // xhr.open("GET", "http://192.168.2.185/get?humidity=0", true);
            xhr.open("GET", get_url, true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var responseText = xhr.responseText;
                    document.getElementById('label_id_st').innerHTML = responseText;
                    
                    var jsonObject = JSON.parse(responseText); // 解析 JSON 字符串为 JavaScript 对象
                    var sssValue = jsonObject.设置; // 获取 "sss" 值
                    console.log("设置=",sssValue);
                    input_set = document.getElementById('input_set');
                    input_set.value =  sssValue;
                }
            };

            xhr.send();
        }

        function set_act_val() {
            var inputval = document.getElementById("input_set");
            console.log("inputval=", inputval.value)
            if (inputval.value.trim() === "")
            {
                alert("设置不能为空");
            }
            else
            {
                var input_ip = document.getElementById("textInput_ip");
                var ip_str = input_ip.value;
                var set_url = "get_plant.php/get?set=1&&val="+inputval.value+"&&ip="+ip_str
                // console.log("set_url", set_url)
                var xhr = new XMLHttpRequest();
                xhr.open("GET", set_url, true);

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var responseText = xhr.responseText;
                     
                        console.log("设置返回结果=",responseText);
                        // input_set = document.getElementById('input_set');
                        // input_set.value =  sssValue;
                    }
                };
                xhr.send();
            }

        }
        function set_dev_push_ip() {
            var inputval = document.getElementById("input_push_ip");
            console.log("inputval=", inputval.value)
            if (inputval.value.trim() === "")
            {
                alert("设置不能为空");
            }
            else
            {
                var input_ip = document.getElementById("textInput_ip");
                var ip_str = input_ip.value;
                var set_url = "get_plant.php/get?set=1&&srvip="+inputval.value+"&&ip="+ip_str
                // console.log("set_url", set_url)
                var xhr = new XMLHttpRequest();
                xhr.open("GET", set_url, true);

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var responseText = xhr.responseText;
                        console.log("设置返回结果=",responseText);
                        // input_set = document.getElementById('input_set');
                        // input_set.value =  sssValue;
                    }
                };
                xhr.send();
            }

        }
        function set_dev_push_period() {
            var inputval = document.getElementById("input_push_period");
            console.log("inputval=", inputval.value)
            if (inputval.value.trim() === "")
            {
                alert("设置不能为空");
            }
            else
            {
                var input_ip = document.getElementById("textInput_ip");
                var ip_str = input_ip.value;
                var set_url = "get_plant.php/get?set=1&&period="+inputval.value+"&&ip="+ip_str
                // console.log("set_url", set_url)
                var xhr = new XMLHttpRequest();
                xhr.open("GET", set_url, true);

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var responseText = xhr.responseText;
                        console.log("设置返回结果=",responseText);
                        // input_set = document.getElementById('input_set');
                        // input_set.value =  sssValue;
                    }
                };
                xhr.send();
            }

        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@3.26.3/dist/apexcharts.min.js"></script>
    <script>
        function show_data_format( xData, yData){
            // var xData = time_x;
            // var yData = humidity_y;
			xData.sort(function(a, b) {
                return a-b;
                // return b-a;
            });
			
			var xData_date = Array(xData.length);
			for (var i = 0; i < xData.length; i++) {
				// 待转换的秒时间戳
				var timestamp = xData[i];
				// 将秒时间戳转换为日期对象
				var date = new Date(timestamp * 1000);
				// var year = date.getFullYear();
				// var month = date.getMonth() + 1;
				// var day = date.getDate();
				var hours = date.getHours();
				var minutes = date.getMinutes();
				var seconds = date.getSeconds();
				xData_date[i] = hours.toString()+":"+minutes.toString();
				console.log(xData_date[i] );
			}
            // 创建配置对象
            var options = {
                series: [{
                    name: 'hmdy',
                    data: yData
                }],
                chart: {
                    type: 'line',
                    height: 350
                },
                xaxis: {
                    categories: xData_date
                }
            };
            return  options;
        }
        document.addEventListener("DOMContentLoaded", function () {
            // JSON数据
            var jsonData = {
                'time': [1690190502, 1690190622, 1690190742],
                'hmdy': [200, 500, 300]
            };
            var data_show = show_data_format(jsonData['time'], jsonData['hmdy']);
            var chart = new ApexCharts(document.querySelector("#chart"), data_show); // 创建图表对象
            chart.render();      // 渲染图表
        
            // 获取并显示网址内容的函数
            function fetchData() {
                var label = document.querySelector("#label");
                var inputval = document.getElementById("input_nums");
                var url = 'plant_sql.php/ins=0?get=hist&&pagesize='+inputval.value.toString()+'&&pagenum=0';
                console.log(url);
                fetch(url)
                    .then(response => response.text())
                    .then(data => {
                        // console.log(data)
                        var jsonObject = JSON.parse(data);
                        options_new = show_data_format(jsonObject.his_tm, jsonObject.his_hum);
                        // 更新图表数据
                        chart.updateSeries(options_new.series);
                        chart.updateOptions({
                            xaxis: options_new.xaxis
                        });
                    })
                    .catch(error => console.log(error));
            }
            var his_data_offset = 0
            function refreshBtn_back_cb() {
                var inputval = document.getElementById("offset_unit");
                his_data_offset += parseInt(inputval.value)
                var inputval = document.getElementById("input_nums");
                var url = 'plant_sql.php/ins=0?get=hist&&pagesize='+inputval.value.toString()+'&&pagenum='+his_data_offset.toString();
                console.log(url);
                fetch(url)
                    .then(response => response.text())
                    .then(data => {
                        // console.log(data)
                        var jsonObject = JSON.parse(data);
                        options_new = show_data_format(jsonObject.his_tm, jsonObject.his_hum);
                        // 更新图表数据
                        chart.updateSeries(options_new.series);
                        chart.updateOptions({
                            xaxis: options_new.xaxis
                        });
                    })
                    .catch(error => console.log(error));
            }
            function refreshBtn_foward_cb() {
                var inputval = document.getElementById("offset_unit");
                if(his_data_offset-parseInt(inputval.value) >= 0)
                {   
                    his_data_offset -= parseInt(inputval.value);
                }
                else
                {
                    alert("no data");
                }
                var inputval = document.getElementById("input_nums");
                var url = 'plant_sql.php/ins=0?get=hist&&pagesize='+inputval.value.toString()+'&&pagenum='+his_data_offset.toString();
                console.log(url);
                fetch(url)
                    .then(response => response.text())
                    .then(data => {
                        // console.log(data)
                        var jsonObject = JSON.parse(data);
                        options_new = show_data_format(jsonObject.his_tm, jsonObject.his_hum);
                        // 更新图表数据
                        chart.updateSeries(options_new.series);
                        chart.updateOptions({
                            xaxis: options_new.xaxis
                        });
                    })
                    .catch(error => console.log(error));
            }

            // 刷新按钮点击事件处理程序
            var refreshBtn = document.querySelector("#refreshBtn");
            refreshBtn.addEventListener("click", fetchData);
            
            var refreshBtn_back = document.querySelector("#refreshBtn_back");
            refreshBtn_back.addEventListener("click", refreshBtn_back_cb);
            
            var refreshBtn_foward = document.querySelector("#refreshBtn_foward");
            refreshBtn_foward.addEventListener("click", refreshBtn_foward_cb);
        });
        </script>
                    <style>
                        .my-button {
                          width: 80px;
                          height: 30px;
                          margin-left: 10px;
                        }
                    </style>
</head>
<body>
    <div class="rectangle">
        <span class="text">testtest</span>
    </div>
    <div class="container">
        <label style="margin-top: 10px;">访问设备IP地址:
            <input type="text" id="textInput_ip" width="150px" placeholder="192.168.2.185">
            <button class="my-button" onclick="saveData()">保存</button>
            <button class="my-button" onclick="loadData()">读取</button>
        </label>


    </div>


    <div class="container">
        <label id="label_id_st">当前无任何状态,手动刷新</label>
        <!-- <label style="margin-top: 10px;background-color: rgb(64, 125, 247);"> -->
            <button class="my-button" onclick="get_plant_status()">状态刷新</button>
        <!-- </label> -->
        
        <label class="settinglabel" >浇水阈值100-700(越大越干燥):
            <input type="text" id="input_set" width="150px" placeholder="400">
            <button class="my-button" onclick="set_act_val()">设置</button>
        </label>
        <label class="settinglabel">设备上报IP:
            <input type="text" id="input_push_ip" width="150px" placeholder="192.168.2.126">
            <button class="my-button" onclick="set_dev_push_ip()">设置</button>
        </label>
        <label class="settinglabel">设备上报周期(最小60s):
            <input type="text" id="input_push_period" width="150px" placeholder="60">
            <button class="my-button" onclick="set_dev_push_period()">设置</button>
        </label>
        <label class="settinglabel" >
            <!-- <input type="text" id="input_param_set" width="150px" placeholder="400"> -->
        </label>
        <button class="my-button" onclick="get_plant_settings()">获取参数</button>
    </div>
    <div class="container">
        
        
        <div id="chart"></div>
        <div style="width: 70%;height: 100%; border: #191a19;text-align: right;">
            <label>
                <label class="my-button">单页数据:
                    <input type="text" id="input_nums"  placeholder="10" value="100">
                </label>
                <button id="refreshBtn"  class="my-button">最新</button>
            </label>
            <br />
            <br />
            <label style="margin-top: 10px;">步长:
                <input type="text" id="offset_unit" width="50px" value="10">
                <button id="refreshBtn_back" class="my-button">向后</button>
                <button id="refreshBtn_foward" class="my-button">向前</button>
            </label>
        </div>
    </div>
</body>
</html>